package com.kgc.itrip.controller;

import com.kgc.itrip.common.*;
import com.kgc.itrip.component.MailTools;
import com.kgc.itrip.component.RedisTools;
import com.kgc.itrip.component.SmsTools;
import com.kgc.itrip.dto.Dto;
import com.kgc.itrip.vo.ItripUserVO;
import com.kgc.itrip.pojo.ItripUser;
import com.kgc.itrip.response.ResultCode;
import com.kgc.itrip.service.*;
import freemarker.template.TemplateException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 系统用户控制器
        *
        */
@Api(value = "用户控制器")
@RestController
@RequestMapping("/api")
public class UserController {
    @Resource
    private ItripUserService userService;
    @Resource
    private MailTools mailTools;
    @Resource
    private SmsTools smsTools;
    @Resource
    private RedisTools redisTools;

    @ApiOperation(value = "验证是否已存在该用户名",
            httpMethod = "GET",notes = "验证是否已存在该用户名",
            protocols = "http",produces = "application/json;charset=UTF-8",
            consumes = "application.json")
    @GetMapping(value = "/ckusr")
    public Dto ckusr(@RequestParam String name) throws Exception{
        if (EmptyUtils.isEmpty(name)){//表示没有传入name值
            return DtoUtil.returnFail(ResultCode.PARAM_IS_NULL.getMsg(),
                    ResultCode.PARAM_IS_NULL.getCode());
        }
        //调出业务逻辑层去查询
        Dto dto = userService.isExisitByName(name);
        return dto;
    }

    @ApiOperation(value = "邮箱注册",
            httpMethod = "POST",notes = "邮箱注册",
            protocols = "http",produces = "application/json;charset=UTF-8",
            consumes = "application/json")
    @PostMapping(value="/doregister")
    public Dto doregister(@RequestBody ItripUserVO userVO) throws Exception {
        if(EmptyUtils.isEmpty(userVO)){
            return DtoUtil.returnFail(ResultCode.PARAM_IS_NULL.getCode(),ResultCode.PARAM_IS_NULL.getMsg());
        }
        if(EmptyUtils.isEmpty(userVO.getUserCode())){
            return DtoUtil.returnFail(ResultCode.EMAIL_IS_NULL.getCode(),ResultCode.EMAIL_IS_NULL.getMsg());
        }
        if(EmptyUtils.isEmpty(userVO.getUserPassword())){
            return DtoUtil.returnFail(ResultCode.PASSWORD_IS_NULL.getCode(),ResultCode.PASSWORD_IS_NULL.getMsg());
        }
        ItripUser itripUser = new ItripUser();
        BeanUtils.copyProperties(userVO,itripUser);
        userService.itriptxAddItripUser(itripUser);
        //发送短信验证码
        sendEmailCode(userVO.getUserCode());
        return DtoUtil.returnSuccess("注册成功");
    }

    @ApiOperation(value = "邮箱注册用户验证",
            httpMethod = "PUT",notes = "邮箱注册用户验证",
            protocols = "http",produces = "application/json;charset=UTF-8",
            consumes = "application.json")
    @PutMapping(value="/activate")
    public Dto activate(@RequestParam String user,
                             @RequestParam String code) throws Exception{
        if(EmptyUtils.isEmpty(user)){
            return DtoUtil.returnFail(ResultCode.USERCODE_IS_NULL.getCode(),ResultCode.USERCODE_IS_NULL.getMsg());
        }
        if(EmptyUtils.isEmpty(code)){
            return DtoUtil.returnFail(ResultCode.CODE_IS_NULL.getCode(),ResultCode.CODE_IS_NULL.getMsg());
        }
        Dto dto = userService.itriptxActiveEmail(user,code);
        return dto;
    }

    @ApiOperation(value = "使用手机注册",
            httpMethod = "POST",notes = "使用手机注册",
            protocols = "http",produces = "application/json;charset=UTF-8",
            consumes = "application.json")
    @PostMapping(value = "/registerbyphone")
    public Dto registerbyphone(@RequestBody ItripUserVO userVO) throws Exception{
        if(EmptyUtils.isEmpty(userVO)){
            return DtoUtil.returnFail(ResultCode.PARAM_IS_NULL.getCode(),ResultCode.PARAM_IS_NULL.getMsg());
        }
        if(EmptyUtils.isEmpty(userVO.getUserCode())){
            return DtoUtil.returnFail(ResultCode.USERCODE_IS_NULL.getCode(),ResultCode.USERCODE_IS_NULL.getMsg());
        }
        if(EmptyUtils.isEmpty(userVO.getUserPassword())){
            return DtoUtil.returnFail(ResultCode.PASSWORD_IS_NULL.getCode(),ResultCode.PASSWORD_IS_NULL.getMsg());
        }
        //调用业务逻辑层去做添加操作
        ItripUser itripUser = new ItripUser();
        BeanUtils.copyProperties(userVO,itripUser);
        userService.itriptxAddItripUser(itripUser);
        //发送短信验证码
        sendSmsCode(userVO.getUserCode());
        return DtoUtil.returnSuccess("注册成功");
    }
    @ApiOperation(value = "手机注册用户短信验证",
            httpMethod = "PUT",notes = "手机注册用户短信验证",
            protocols = "http",produces = "application/json;charset=UTF-8",
            consumes = "application.json")
    @PutMapping(value="/validatephone")
    public Dto validatePhone(@RequestParam String user,
                             @RequestParam String code) throws Exception{
        if(EmptyUtils.isEmpty(user)){
            return DtoUtil.returnFail(ResultCode.USERCODE_IS_NULL.getCode(),ResultCode.USERCODE_IS_NULL.getMsg());
        }
        if(EmptyUtils.isEmpty(code)){
            return DtoUtil.returnFail(ResultCode.CODE_IS_NULL.getCode(),ResultCode.CODE_IS_NULL.getMsg());
        }
        Dto dto = userService.itriptxActiveAccount(user,code);
        return dto;
    }
    /**
     * 发送激活码的方法
     * @param emailNum
     */
    private void sendEmailCode(String emailNum) throws ParseException, TemplateException, IOException, MessagingException {
        //生成激活码
        int activedCode = MD5.getRandomCode();
        //将激活码保存到redis中 key:smsActiveCode:15885458741   value:code
        redisTools.set(Constants.ACCOUNT_ACTIVE_PREFIX.EMAIL_PREFIX+emailNum,
                activedCode,Constants.SMS_PARAMS.SMS_TIMEOUT);
        //设置激活码
        smsTools.sendPhoneSMS(emailNum,
                Constants.SMS_PARAMS.ACCOUNT_ACTIVED_TEMPLATE,
                new String[]{String.valueOf(activedCode), String.valueOf(Constants.SMS_PARAMS.SMS_TIMEOUT / 60)});
        Map<String,Object> model = new HashMap<>();
        model.put("name",emailNum);
        model.put("code",activedCode);
        model.put("datetime", DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        mailTools.sendTemplateMail("模板邮件",model,"account_active.ftl",emailNum);
    }
    /**
     * 发送激活码的方法
     * @param phoneNum
     */
    private void sendSmsCode(String phoneNum){
        //生成激活码
        int activedCode = MD5.getRandomCode();
        //将激活码保存到redis中 key:smsActiveCode:15885458741   value:code
        redisTools.set(Constants.ACCOUNT_ACTIVE_PREFIX.SMS_PREFIX+phoneNum,
                activedCode,Constants.SMS_PARAMS.SMS_TIMEOUT);
        //设置激活码
        smsTools.sendPhoneSMS(phoneNum,
                Constants.SMS_PARAMS.ACCOUNT_ACTIVED_TEMPLATE,
                new String[]{String.valueOf(activedCode), String.valueOf(Constants.SMS_PARAMS.SMS_TIMEOUT / 60)});
    }
}
